package com.demo.utils;


import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.DEFAULT_CHARSET;

public class CommonUtils {

    public static String DOU_YIN_BASE_URL = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=";

    public static String HUO_SHAN_BASE_URL = " https://share.huoshan.com/api/item/info?item_id=";

    public static String DOU_YIN_DOMAIN = "douyin";

    public static String HUO_SHAN_DOMAIN = "huoshan";

    public static String getLocation(String url) {
        try {
            URL serverUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setInstanceFollowRedirects(false);
            conn.setRequestProperty("User-agent", "ua");//模拟手机连接
            conn.connect();
            String location = conn.getHeaderField("Location");
            return location;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String matchNo(String redirectUrl) {
        List<String> results = new ArrayList<>();
        Pattern p = Pattern.compile("video/([\\w/\\.]*)/");
        Matcher m = p.matcher(redirectUrl);
        while (!m.hitEnd() && m.find()) {
            results.add(m.group(1));
        }
        return results.get(0);
    }

    public static String hSMatchNo(String redirectUrl) {

        List<String> results = new ArrayList<>();
        Pattern p = Pattern.compile("item_id=([\\w/\\.]*)&");
        Matcher m = p.matcher(redirectUrl);
        while (!m.hitEnd() && m.find()) {
            results.add(m.group(1));
        }
        return results.get(0);
    }

    public static byte[] get(String url) throws IOException {
        //网络下载
        HttpURLConnection conn = (HttpURLConnection) new URL
                (url).openConnection();

        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = null;

        if (conn.getResponseCode() == 200) {
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[8 * 1024];//8k
            int len = -1;

            //获取资源的总长度
            int totalLen = conn.getContentLength();
            int curLen = 0;
            while ((len = is.read(buffer)) != -1) {

                baos.write(buffer, 0, len);
                //3.计算下载 进度
                curLen += len;
                int p = curLen * 100 / totalLen;
                System.out.println("jindu" + p + "%");

            }

            is.close();
            conn.disconnect();

        }
        return baos.toByteArray();
    }


    public static void doGet(HttpServletResponse response, String remoteFileUrl, String fileName) throws IOException {

        if (StringUtils.isEmpty(remoteFileUrl)) {
            throw new RuntimeException("remoteFileUrl is invalid!");
        }
        URL url = new URL(remoteFileUrl);
        BufferedInputStream in = null;
        // 这和上面两句一样的效果
        in = new BufferedInputStream(url.openStream());
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        int i;
        while ((i = in.read()) != -1) {
            response.getOutputStream().write(i);
        }
        in.close();
        response.getOutputStream().close();
    }

    public static String doGet(String baseUrl, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = baseUrl;
            if (param != null) {
                urlNameString = baseUrl + "?" + param;
            }
            URL realUrl = new URL(urlNameString);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
            connection.setRequestProperty("Charsert", DEFAULT_CHARSET);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                Map<String, List<String>> map = connection.getHeaderFields();
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}
